﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Dynamo
{
    public enum CodeBlockType { Html, Jint };
    public class CodeBlock
    {
        public int Order { get; set; }
        public string Script { get; set; }
        public CodeBlockType CodeBlockType { get; set; }


        private static string CodeOpen = "@{";
        private static string CodeClose = "}@";
        /// <summary>
        /// Script is a mix of html and source code blocks
        /// Always assume that it is HTML unless the text is encapuslated in @{ ... }
        /// </summary>
        /// <param name="Script"></param>
        /// <returns></returns>
        public static List<CodeBlock> ProcessScriptToCodeBlocks(string Script)
        {
            List<CodeBlock> blocks = new List<CodeBlock>();

            if (!Script.Contains(CodeOpen))
            {
                blocks.Add(new CodeBlock() { CodeBlockType = CodeBlockType.Html, Order = 0, Script = Script });
            }
            else
            {
                int order = 0;

                string s = Script.Trim();

                int index = s.IndexOf(CodeOpen);
                while (index >= 0)
                {
                    if (index > 1)
                    {
                        string section = s.Substring(0, index);
                        blocks.Add(new CodeBlock() { CodeBlockType = CodeBlockType.Html, Order = order, Script = section });
                        s = s.Substring(index);
                    }
                    else
                    {
                        string section = "";
                        if (s.IndexOf(CodeClose) < 0) s += CodeClose;
                        section = s.Substring(CodeOpen.Length, s.IndexOf(CodeClose) - CodeOpen.Length);
                        
                        if (section.StartsWith("=")) section = "echo(" + section.Substring(1, section.Length - 1) + ");";
                        blocks.Add(new CodeBlock() { CodeBlockType = CodeBlockType.Jint, Order = order, Script = section });
                        s = s.Substring(s.IndexOf(CodeClose) + CodeClose.Length);
                    }
                    index = s.IndexOf(CodeOpen);
                    order++;
                }
                if (s.Trim().Length > 0)
                {
                    blocks.Add(new CodeBlock() { CodeBlockType = CodeBlockType.Html, Order = order, Script = s });
                }

            }

            return blocks;
        }


    }
}